package com.weiyuwqj.server.service.invest.module;

import com.weiyuwqj.api.common.Calculator;
import com.weiyuwqj.api.constant.ItemStatus;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.exception.HfException;
//import com.weiyuwqj.api.hengfeng.model.base.HfBaseResponseBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfDataBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.platform.HfFundFreezeOrTraw;
import com.weiyuwqj.api.model.*;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.RandomCodesUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.mapper.*;
//import com.weiyuwqj.server.pay.PlatformApi;
import com.weiyuwqj.server.service.account.module.DealAction;
import com.weiyuwqj.server.service.account.module.DealModule;
import com.weiyuwqj.server.service.account.module.action.user.invest.InvestDealAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by huzj on 2017/3/28.
 */
@Component
public class AssetInvestModule {

    @Autowired
    private BasAssetsPackageMapper assetsPackageMapper;
    @Autowired
    private BusAccountMapper accountMapper;
    @Autowired
    private BusAssetPackagePlanMapper assetPackagePlanMapper;
    @Autowired
    private BusAssetPackageInvestMapper packageInvestMapper;
    @Autowired
    private BusUserStatMapper userStatMapper;
    @Autowired
    private DealModule dealModule;
    @Autowired
    private BusAssetInvestMapper assetInvestMapper;
    @Autowired
    private BasItemMapper itemMapper;
    @Autowired
    private BusVerifyLogMapper verifyLogMapper;
    @Autowired
    private BasUserMapper userMapper;
//    @Autowired
//    private PlatformApi platformApi;

//    public List<Map> doInvest(Integer userId, BigDecimal amount, BusAssetPackagePlan packagePlan, Integer investType) {
//        //判断项目是否存在
//        if (packagePlan == null) {
//            throw new CrowdException("packagePlan.not_exist");
//        }
//
//        BigDecimal totalAmount = packagePlan.getAmount();
//        BigDecimal onGoingAmount = packagePlan.getOngoingAccount() == null ?
//                BigDecimal.ZERO : packagePlan.getOngoingAccount();
//        BigDecimal remainAmount = totalAmount.subtract(onGoingAmount);
//        BigDecimal investAmount = amount;
//
//
//        //判断用户登录状态
//        if (null == userId || userId < 1) {
//            throw new CrowdException("item.invest.session_out");
//        }
//
//        //判断投资金额是否是每份的整数倍
//        BasAssetsPackage assetsPackage = assetsPackageMapper.selectByPrimaryKey(packagePlan.getAssetPackageId());
//        BigDecimal remainder = amount.divideAndRemainder(assetsPackage.getEachAmount())[1];
//        if (remainder.compareTo(BigDecimal.ZERO) != 0) {
//            throw new CrowdException("invest.amount_must_be_integer_times");
//        }
//
//        //判断包计划状态
//        if (packagePlan.getStatus() != 2) {
//            throw new CrowdException("item.status_is_not_right");
//        }
//
//        //判断可投余额
//        if (remainAmount.compareTo(amount) < 0) {
//            throw new CrowdException("item.invest.item_no_more_balance");
//        }
//
//        //判断用户可用余额
//        BusAccount account = accountMapper.getBusAccountByUserId(userId);
//        BigDecimal accountCash = account.getCash();
//        BigDecimal accountUsable = account.getUsable();
//        if (accountCash.compareTo(investAmount) < 0 || accountUsable.compareTo(investAmount) < 0) {
//            throw new CrowdException("account_has_no_more_money");
//        }
//
//        //更新项目状态
//        BigDecimal newOnGoingAmount = onGoingAmount.add(amount);
//        BigDecimal scale;
//        if (newOnGoingAmount.compareTo(totalAmount) < 0) {
//            scale = newOnGoingAmount.multiply(new BigDecimal(100)).
//                    divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
//            packagePlan.setOngoingAccount(newOnGoingAmount);
//            packagePlan.setScale(scale);
//        } else {
//            scale = new BigDecimal(100);
//            assetPackagePlanMapper.updatePackagePlanStatus(2, 3, packagePlan.getId());
//            Map map = new HashMap();
//            map.put("fullTime", new Date());
//            map.put("planId", packagePlan.getId());
//            assetPackagePlanMapper.updateFullTime(map);
//        }
//
//        //更新资产包计划表进度和金额
//        int count = assetPackagePlanMapper.updateAmountAndScale(amount, onGoingAmount, scale, packagePlan.getId());
//        if (count < 1) {
//            throw new CrowdException("item.invest.busy");
//        }
//
//        //插入债转投资记录
//        BusAssetPackageInvest packageInvest = new BusAssetPackageInvest();
//        packageInvest.setPackagePlanId(packagePlan.getId());
//        packageInvest.setUserId(userId);
//        packageInvest.setInvestType(investType);
//        packageInvest.setInvestAmount(investAmount);
//        packageInvest.setAddip(IpUtils.get());
//        packageInvest.setAddtime(new Date());
//        packageInvest.setStatus(2);
//        //计算收益
//        BasItem basItem = new BasItem();
//        basItem.setItemCycle(packagePlan.getCycle());
//        basItem.setItemRate(packagePlan.getRate());
//        basItem.setItemAddRate(BigDecimal.ZERO);
//        BigDecimal interest = Calculator.addRateInterest(investAmount, basItem);
//        packageInvest.setInterest(interest);
//
//        packageInvestMapper.insertPackageInvest(packageInvest);
//
//        //统计投资
//        Map investMap = new HashMap();
//        investMap.put("userId", userId);
//        investMap.put("investAmount", investAmount);
//        userStatMapper.updateInvest(investMap);
//
//        //操作用户金额
//        String remark = packagePlan.getPackagePlanName() + "投资冻结" + investAmount + "元";
//        DealAction action = new InvestDealAction();
//        action.deal(userId, amount, remark);
//        count = dealModule.dealAction(action);
//        if (count < 1) {
//            throw new CrowdException("item.invest.busy");
//        }
//
//        List<Map> list = new ArrayList<>();
//        //第一期生成资产投资记录
//        if (packagePlan.getPeriods() == 1) {
//            List<BasItem> itemList = itemMapper.listUnderByPackageId(assetsPackage.getId());
//            BigDecimal remainInvestAmount = investAmount;
//            for (BasItem item : itemList) {
//                //剩余投资金额小于等于0
//                if (remainInvestAmount.compareTo(BigDecimal.ZERO) <= 0) {
//                    break;
//                }
//
//                BigDecimal itemRemainAmount = item.getItemAccount().subtract(item.getItemOngoingAccount());
//                BigDecimal itemScale;
//                BigDecimal itemInvestAmount;
//
//                //项目可投金额小于等于0
//                if (itemRemainAmount.compareTo(BigDecimal.ZERO) <= 0) {
//                    continue;
//                }
//                if (remainInvestAmount.compareTo(itemRemainAmount) >= 0) {
//                    //投资金额大于标的剩余金额
//                    remainInvestAmount = remainInvestAmount.subtract(itemRemainAmount);
//                    itemInvestAmount = itemRemainAmount;
//                    //更新债转项目状态
//                    count = itemMapper.updateItemStatus(ItemStatus.OPEN, ItemStatus.FULL_COMPLETE, item.getId());
//                    if (count < 1) {
//                        throw new CrowdException("item.invest.busy");
//                    }
//                    itemScale = new BigDecimal(100);
//
//                    //插入日志类型3
//                    BusVerifyLog log = new BusVerifyLog();
//                    log.setOperateUserId(1);
//                    log.setContent("项目满标：" + item.getItemName());
//                    log.setAddtime(new Date());
//                    log.setType((byte) 3);
//                    log.setItemId(item.getId());
//                    log.setStatus((byte) 1);
//                    log.setAddip(IpUtils.get());
//                    verifyLogMapper.insert(log);
//                } else {
//                    //投资金额小于标的剩余金额
//                    itemInvestAmount = remainInvestAmount;
//                    remainInvestAmount = BigDecimal.ZERO;
//                    itemScale = (itemInvestAmount.add(item.getItemOngoingAccount())).
//                            multiply(new BigDecimal(100)).
//                            divide(item.getItemAccount(), 2, BigDecimal.ROUND_DOWN);
//                }
//
//                //更新债转项目金额和进度
//                count = itemMapper.updateItemScale(itemInvestAmount, item.getItemOngoingAccount(), itemScale, item.getId());
//                if (count < 1) {
//                    throw new CrowdException("debt.invest.busy");
//                }
//
//                //插入投资记录
//                String investOrder = RandomCodesUtils.getOrderNo();
//                BusAssetInvest assetInvest = new BusAssetInvest();
//                assetInvest.setUserId(userId);
//                assetInvest.setItemId(item.getId());
//                assetInvest.setParentId(0);
//                assetInvest.setInvestType(investType);
//                assetInvest.setInvestCurrent(1);
//                assetInvest.setInvestOrder(investOrder);
//                assetInvest.setInvestStatus(0);
//                assetInvest.setPackagePlanId(packagePlan.getId());
//                assetInvest.setDebtTransferStatus(0);
//                assetInvest.setInvestAmount(itemInvestAmount);
//                assetInvest.setInvestDealAmount(itemInvestAmount);
//                BigDecimal earnRate;
//                //计算日期
//                switch (packagePlan.getCycleUnit()) {
//                    case 1:
//                        earnRate = packagePlan.getRate().
//                                multiply(new BigDecimal(packagePlan.getCycle())).
//                                divide(new BigDecimal(360), 6, BigDecimal.ROUND_DOWN);
//                        break;
//                    case 2:
//                        earnRate = packagePlan.getRate().
//                                multiply(new BigDecimal(packagePlan.getCycle())).
//                                divide(new BigDecimal(52), 6, BigDecimal.ROUND_DOWN);
//                        break;
//                    case 3:
//                        earnRate = packagePlan.getRate().
//                                multiply(new BigDecimal(packagePlan.getCycle())).
//                                divide(new BigDecimal(12), 6, BigDecimal.ROUND_DOWN);
//                        break;
//                    case 4:
//                        earnRate = packagePlan.getRate().
//                                multiply(new BigDecimal(packagePlan.getCycle())).
//                                divide(new BigDecimal(4), 6, BigDecimal.ROUND_DOWN);
//                        break;
//                    case 5:
//                        earnRate = packagePlan.getRate().
//                                multiply(new BigDecimal(packagePlan.getCycle())).
//                                divide(new BigDecimal(1), 6, BigDecimal.ROUND_DOWN);
//                        break;
//                    default:
//                        earnRate = BigDecimal.ZERO;
//                }
//
//                BigDecimal earnAmount = itemInvestAmount.multiply(earnRate).
//                        divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
//                assetInvest.setCollectAmount(itemInvestAmount.add(earnAmount));
//                assetInvest.setCollectPrincipal(itemInvestAmount);
//                assetInvest.setCollectInterest(earnAmount);
//                assetInvest.setActualCollectAmount(BigDecimal.ZERO);
//                assetInvest.setActualCollectInterest(BigDecimal.ZERO);
//                assetInvest.setActualCollectPrincipal(BigDecimal.ZERO);
//                assetInvest.setActualUncollectAmount(BigDecimal.ZERO);
//                assetInvest.setActualUncollectInterest(BigDecimal.ZERO);
//                assetInvest.setActualUncollectPrincipal(BigDecimal.ZERO);
//                assetInvest.setAdditionalRateAmount(BigDecimal.ZERO);
//                assetInvest.setAddip(IpUtils.get());
//                assetInvest.setAddtime(new Date());
//                assetInvest.setUpdatetime(new Date());
//                assetInvestMapper.insert(assetInvest);
//
//                //冻结投资人资金(未知红包出款方，还需冻结红包出款方红包资金金额)
//                HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//                freezeOrTraw.setAmount(assetInvest.getInvestDealAmount().toString());
//                freezeOrTraw.setFreeze_flg("01");
//                freezeOrTraw.setPlatcust(userMapper.selectByPrimaryKey(userId).getPlatformId());
//                freezeOrTraw.setRemark(userId + "投资冻结");
//                freezeOrTraw.setOrder_no(StringUtils.getOrderNo());
//	            HfResultBean<HfDataBean> result = platformApi.doFundFreeze(freezeOrTraw); // 请求恒丰
//	            if (!result.isSuccess()) { // 成功订单数量为0则抛出异常
//		            throw new HfException("HfException", result.getMessageText());
//	            }
//                //修改冻结流水号
//                String freezeOrderNo = "";
//	            if (result.getData() != null) {
//		            freezeOrderNo = result.getData().getQuery_id();
//	            }
//                assetInvestMapper.modifyAssetInvestFreezeOrderNo(freezeOrderNo, investOrder);
//            }
//        } else {
//            //冻结投资人资金(未知红包出款方，还需冻结红包出款方红包资金金额)
//            HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//            freezeOrTraw.setAmount(investAmount.toString());
//            freezeOrTraw.setFreeze_flg("01");
//            freezeOrTraw.setPlatcust(userMapper.selectByPrimaryKey(userId).getPlatformId());
//            freezeOrTraw.setRemark(userId + "投资冻结");
//            freezeOrTraw.setOrder_no(StringUtils.getOrderNo());
//	        HfResultBean<HfDataBean> resultBean = platformApi.doFundFreeze(freezeOrTraw);// 请求恒丰
//	        //修改冻结流水号
//            String freezeOrderNo = "";
//	        if (resultBean.getData() != null) {
//		        freezeOrderNo = resultBean.getData().getQuery_id();
//	        }
//            packageInvestMapper.modifyPackageInvestFreezeOrderNoById(freezeOrderNo, packageInvest.getId());
//        }
//        return list;
//    }

}
